
package com.rasenhund.android.paintstock;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.NumberPicker;
import android.widget.SeekBar;
import android.widget.Toast;

import com.rasenhund.android.paintstock.dao.StockDao;
import com.rasenhund.android.paintstock.schema.Stock;

/**
 * 在庫登録ダイアログ
 */
@SuppressLint("ValidFragment")
public class EditDialogFragment extends DialogFragment {

    // パラメータ受け渡し用キー
    public static final String KEY_PARAM_NAME = "Name";
    public static final String KEY_PARAM_RESULT = "Result";

    private Callback mCallback = null;
    private Context mContext;

    NumberPicker mNumStock = null; // 本数
    SeekBar mSeekAmount = null; // 残量%

    private Stock mStock = null;

    private int iStartStock = 0;
    private int iStartAmount = 0;

    public EditDialogFragment() {
        // TODO Auto-generated constructor stub
    }

    public EditDialogFragment(Callback targetFragment) {
        setTargetFragment((Fragment) targetFragment, 0);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // 呼び出し元からパラメータ取得
        String sName = getArguments().getString(KEY_PARAM_NAME);

        // コールバックメソッドの実装チェック
        if (getTargetFragment() != null && getTargetFragment() instanceof Callback) {
            mCallback = (Callback) getTargetFragment();
        } else if (getActivity() instanceof Callback) {
            mCallback = (Callback) getActivity();
        }

        mContext = getActivity().getApplicationContext();
        LayoutInflater inflater = getActivity().getLayoutInflater();

        // Viewの初期設定
        View view = inflater.inflate(R.layout.dialog_edit, null);
        mNumStock = (NumberPicker) view.findViewById(R.id.numStock);
        mNumStock.setMinValue(0);
        mNumStock.setMaxValue(99);

        mSeekAmount = (SeekBar) view.findViewById(R.id.seekAmount);
        mSeekAmount.setOnSeekBarChangeListener(seekAmount_OnSeekBarChangeListener);

        // 初期データ取得
        StockDao dao = new StockDao(mContext);
        mStock = dao.selectAt(sName);

        if (mStock != null) {
            mNumStock.setValue(mStock.getStock());
            mSeekAmount.setProgress(mStock.getAmount());
        }

        Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);
        builder.setTitle(sName);
        builder.setPositiveButton("OK", okButton_OnClickListener);

        AlertDialog dialog = builder.create();

        return dialog;

    }

    /**
     * OKボタン押下時処理
     */
    private OnClickListener okButton_OnClickListener = new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {

            if (mStock == null) {
                mStock = new Stock();
            }

            // 最新の値を取得
            mStock.setStock(mNumStock.getValue());
            mStock.setAmount(mSeekAmount.getProgress());

            // 登録処理
            StockDao dao = new StockDao(mContext);
            long lRet = 0;

            if (mStock.get_id() > 0) {
                // update
                lRet = dao.update(mStock);
            } else {
                // insert
                lRet = dao.insert(mStock);
            }

            if (lRet > 0) {
                Toast.makeText(mContext, "登録しました",
                        Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(mContext, "登録に失敗しました",
                        Toast.LENGTH_SHORT).show();
            }

            if (mCallback != null) {
                Bundle args = getArguments();
                // // 登録後の在庫情報をセット
                // args.putSerializable(EditDialogFragment.KEY_PARAM_RESULT,
                // mStock);
                mCallback.onRegistCompleted(getTag(), args, which);
            }

        }
    };

    /**
     * SeekBar変更時の処理
     */
    private SeekBar.OnSeekBarChangeListener seekAmount_OnSeekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            iStartStock = mNumStock.getValue();
            iStartAmount = mSeekAmount.getProgress();
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // 0本、0% -> 1%以上に変更で自動で本数を増やす
            if (iStartAmount == 0 && iStartAmount == 0 && seekBar.getProgress() > 0) {
                mNumStock.setValue(1);
            }
        }
    };

    /**
     * コールバック処理
     */
    public interface Callback {

        void onRegistCompleted(String tag, Bundle args, int which);

    }

}
